module.exports = app => {
    const express = require('express')
    const customer = require('../../models/customer')
    const order = require('../../models/Order')
    const a = require('./a.js')
    const router = express.Router({
        mergeParams: true
    })

    router.get('/order', async (req, res) => {
        const token = req.query.token
        await customer.find({ token: token }).populate([{ path: 'orders', populate: { path: 'goods_list.id' } }]).exec((err, order) => {
            err ? res.send('服务器错误...') : res.send(order[0].orders)
        })
    })

    router.delete('/order', async (req, res) => {
        console.log(req.body)
        var remove = await order.findOneAndRemove({ _id: req.body.date._id })
        console.log(remove)
        await customer.find({ token: req.body.token }).populate([{ path: 'orders', populate: { path: 'goods_list.id' } }]).exec((err, order) => {
            err ? res.send('服务器错误...') : res.send(order[0].orders)
        })
    })

    //打印订单、、、
    router.post('/getorderexcel', async (req, res) => {
        let reqs = req.body
        let cash_fee = reqs.cash_fee    //总金额
        let order_time = reqs.order_time    //下单时间
        let out_trade_no = reqs.out_trade_no    //订单号
        let name = reqs.address[0].name
        let phone = reqs.address[0].phone
        let local = reqs.address[0].local
        let goods_list = []
        reqs.goods_list.filter(item=>{
            goods_list.push({
                name:item.id.name,
                value:item.value ,
                price:item.id.price
            })
            return true
        })
        let beizhu = reqs.beizhu
        var openid = ''
        var taskid = 0
        //引入编码模块
        var iconv = require("iconv-lite");
        //引入 printhelper 模块
        var printhelper = require("./printhelper.js");
        //设备编号
        var uuid = "7cf40e2ff60f7628";
        //第一次
        new Promise((resolve, reject) => {
           //用户绑定
            var data = {
                Uuid: uuid,
                UserId: "13672652751" //0改成您系统的用户编号（自己定义）最好是数字
            }
            //请求回调
            function userBindCallBack(result) {
                openid = JSON.parse(result).OpenUserId
                //处理您的业务逻辑
                //返回格式 {"OpenUserId":160715,"Code":200,"Message":"成功"}
                resolve(openid)
            }
            printhelper.userBind(data, userBindCallBack)
        })
        .then(async data => {
            //获取设备状态
            data = {
                Uuid: uuid
            }
            //请求回调
            function getDeviceStateCallBack(result) {
                //处理您的业务逻辑
                //返回格式 {"State":0,"Code":200,"Message":"成功"} state:代表设备状态，详见api文档
                console.log("设备状态==" + result);
            }
            printhelper.getDeviceState(data, getDeviceStateCallBack);
            //第二次
            new Promise((resolve, reject) => {
                //提交打印
                var title = '            昵家社区超市' + '\n'
                var title2 = '        ' + name + '-' + phone + '\n'
                var title3 = '    自提点：' + local +"服务点"+'\n'
                var title4 = '商品'
                var title5 = '数量   '
                var title6 = '单价'
                var title7 = []
                let title8 = '\n下单时间：' + order_time
                let title9 = '\n订单号：' + out_trade_no
                let title10 = '\n备注：' + beizhu
                goods_list.unshift({name:title4,value:title5,price:title6})
                goods_list.push({name:'配送费',value:'',price:2})
                goods_list.push({name:'合计',value:'',price:cash_fee})
                goods_list.forEach(item=>{
                    title7.push(a.format(item.name,item.value,item.price,'16','8'))
                    return true
                })
                title7 = title7.join('\n')
                if(beizhu != ''){
                    var content = [title,title2,title3,title7,title8,title9,title10]
                }else{
                    var content = [title,title2,title3,title7,title8,title9]
                }
                content = content.join('')
                var b = new Buffer.from(iconv.encode(content, 'UTF-8'));
                content = b.toString("base64");
                var jsonContent = "[{\"Alignment\":0,\"BaseText\":\"" + content + "\",\"Bold\":0,\"FontSize\":1,\"PrintType\":0}]";
                data = {
                    Uuid: uuid,
                    PrintContent: jsonContent,
                    OpenUserId: openid //改成用户设备绑定返回的OpenUserId即可
                }
                //请求回调
                function printContentCallBack(result) {
                    taskid = JSON.parse(result).TaskId
                    //处理您的业务逻辑
                    //返回格式 {"TaskId":0,"Code":200,"Message":"成功"}  TaskId:任务编号
                    console.log("提交打印==" + result + "taskidssss==" + JSON.parse(result).TaskId);
                    resolve(JSON.parse(result).TaskId)
                }
                printhelper.printContent(data, printContentCallBack);
            })
            .then(async datas => {   
                data = {
                    TaskId: datas //任务编号
                }
                function getTaskStateCallBack(result) {
                    console.log("taskid2=="+data)
                    //处理您的业务逻辑
                    //返回格式 {"State":1,"Code":200,"Message":"成功"} state:代表打印任务状态，详见api文档
                    console.log("taskid==" + result);
                }
                printhelper.getTaskState(data, getTaskStateCallBack);
            })
        })
        res.send(req.query)
        // await customer.find({token:token}).populate([{path:'orders',populate: {path:'goods_list.id'}}]).exec((err,order)=>{
        //     err ? res.send('服务器错误...') : res.send(order[0].orders)
        // })
    })


    app.use('/api/web', router)
}